//
//  CustomListCell.m
//
//  Created by lee jory on 09-10-22.
//  Copyright 2009 Netgen. All rights reserved.
//

#import "CustomListCell.h"
#import "MCFunction.h"
#import "MCUIToolkit.h"

@implementation CustomDataGridComponentDataSource
@synthesize titles,data,fieldTypes,columnWidth;
@end

@implementation CustomDataGridScrollView
@synthesize customListCell;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	if (self.decelerating) {
		return;
	}
	UITouch *t = [touches anyObject];
	if([t tapCount] == 1){
		CustomListCell *d = (CustomListCell*)customListCell;
		int idx = [t locationInView:self].y / d.cellHeight;
		index = idx;
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.65];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationWillStartSelector:@selector(doAction)];
		for(int i=0;i<[d.dataSource.titles count];i++){
			UILabel *l = (UILabel*)[customListCell viewWithTag:idx * d.cellHeight + i + 1000];
			l.alpha = .5;
			UILabel *lSpace = (UILabel*)[customListCell viewWithTag:idx * d.cellHeight + i + 10000];
			lSpace.alpha = .5;
		}
		for(int i=0;i<[d.dataSource.titles count];i++){
			UILabel *l = (UILabel*)[customListCell viewWithTag:idx * d.cellHeight + i + 1000];
			l.alpha = 1.0;
			UILabel *lSpace = (UILabel*)[customListCell viewWithTag:idx * d.cellHeight + i + 10000];
			lSpace.alpha = 1.0;
		}		
		[UIView commitAnimations];
	}
}

- (void)doAction
{
	[customListCell doAction:index];
}

@end

@interface CustomListCell (Private)
//int actionSheetFlag;
//初始化各子视图
-(void)layoutSubView:(CGRect)aRect;
//用数据项填冲数据
-(void)fillData;
@end
@implementation CustomListCell
@synthesize vRight, vLeft, cellHeight, dataSource;
@synthesize dataObjectName;
@synthesize layoutName;
@synthesize listData;
@synthesize listLayout;
@synthesize gridType;
@synthesize tabIndex;
@synthesize viewController;

- (float)cellTitleHeight
{
	return 40.0;
}

-(void)addRightArrow:(UIView*)view
{
}

- (id)initWithFrame:(CGRect)aRect data:(CustomDataGridComponentDataSource*)aDataSource gridType:(NSString *)aGridType{
	self = [super initWithFrame:aRect];
	if(self != nil){
		self.clipsToBounds = YES;
		self.gridType = aGridType;
		if ([self.gridType isEqualToString:@"S"]) {
			self.backgroundColor = [UIColor colorWithPatternImage:[MCUserDefaults instance].skin_bgViewImg];//[UIColor colorWithRed:14.5 green:56.1 blue:76.5 alpha:1];
		}else {
			self.backgroundColor = [UIColor clearColor];
		}
		self.dataSource = aDataSource;
		//初始显示视图及Cell的长宽高
		contentWidth = .0;
		cellHeight = 40.0;
		
		cellWidth = 0;
		for(int i = 0;i<[dataSource.columnWidth count];i++) {
			contentWidth += [[dataSource.columnWidth objectAtIndex:i] intValue];
		}
		int count = [dataSource.columnWidth count];
		if (contentWidth < CGRectGetWidth(aRect) && count>0) {
			float addition = (CGRectGetWidth(aRect) - contentWidth) / (count*1.0);
			for(int i = 0;i<count;i++) {
				int columnWidth = [[dataSource.columnWidth objectAtIndex:i] intValue];
				[dataSource.columnWidth replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%f", columnWidth+addition]];
			}
			contentWidth = CGRectGetWidth(aRect);
		}
		contentHeight = [dataSource.data count] * cellHeight;
		//初始化各视图
		[self layoutSubView:aRect];
		//填冲数据
		[self fillData];
	}
	return self;
}
-(void)layoutSubView:(CGRect)aRect{
	vRightContent = [[UIView alloc] initWithFrame:CGRectMake(0, 0,  CGRectGetWidth(aRect) - cellWidth, contentHeight)];
	vRightContent.backgroundColor = [UIColor colorWithRed:0.667 green:0.722 blue:0.788 alpha:1.000];

	vRightContent.opaque = YES;
	
	vTopRight = [[UIView alloc] initWithFrame:CGRectMake(0, 0,  CGRectGetWidth(aRect) - cellWidth, self.cellTitleHeight)];
	
	vLeft = [[CustomDataGridScrollView alloc] initWithFrame:CGRectMake(0, self.cellTitleHeight, CGRectGetWidth(aRect), aRect.size.height - self.cellTitleHeight)];
	vRight = [[CustomDataGridScrollView alloc] initWithFrame:CGRectMake(0, 0,  CGRectGetWidth(aRect) - cellWidth, contentHeight)];
	
	vLeft.backgroundColor = [UIColor colorWithRed:0.667 green:0.722 blue:0.788 alpha:1.000];
	
	vLeft.customListCell = self;
	vRight.customListCell = self;
	
	vLeft.opaque = YES;
	vRight.opaque = YES;
	vTopRight.opaque = YES;
	
	//设置ScrollView的显示内容
	vLeft.contentSize = CGSizeMake( CGRectGetWidth(aRect), contentHeight);
	vRight.contentSize = CGSizeMake(contentWidth, aRect.size.height - self.cellTitleHeight);
	
	//设置ScrollView参数
	vRight.delegate = self;
	MCUserDefaults *defaults = [MCUserDefaults instance];
	vTopRight.backgroundColor = defaults.skin_bgListLabelSpaceColor;	
	if ([self.gridType isEqualToString:@"S"]) {
		vRight.backgroundColor = [UIColor clearColor];
		vLeft.backgroundColor = [UIColor clearColor];
	}else {
		vRight.backgroundColor = [UIColor clearColor];
		vLeft.backgroundColor = [UIColor clearColor];
	}
	
	//添加各视图
	[vRight addSubview:vRightContent];
	[vRightContent release];
	[vLeft addSubview:vLeftContent];
	[vLeftContent release];
	[vLeft addSubview:vRight];
	[vRight release];
	[self addSubview:vLeft];
	[vLeft release];
	
	[vLeft bringSubviewToFront:vRight];
	[self addSubview:vTopRight];
	[vTopRight release];
}


-(void)fillData{
	float columnOffset = 0.0;
	//填冲标题数据
	for(int column = 0; column < [dataSource.titles count]; column++){
		float columnWidth = [[dataSource.columnWidth objectAtIndex:column] floatValue];
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(columnOffset, 0, columnWidth - 1, self.cellTitleHeight)];
		label.font = [UIFont systemFontOfSize:16.0f];
		NSArray *values = [[dataSource.titles objectAtIndex:column] componentsSeparatedByString:@":-:"];
		label.text = [values objectAtIndex:0];
		label.textColor = [UIColor whiteColor];
		if ([values count] > 1) {
			label.textColor = [MCFunction hexColor:[NSString stringWithFormat:@"%@64", [values objectAtIndex:1]]];
		}
		MCUserDefaults *defaults = [MCUserDefaults instance];
		label.backgroundColor = [UIColor colorWithPatternImage:defaults.skin_bgListLabelImg];
		label.textAlignment = UITextAlignmentCenter;
		
		[vTopRight addSubview:label];
		columnOffset += columnWidth;
		
		[label release];
	}	
	
	//填冲数据内容	
	for(int i = 0;i<[dataSource.data count];i++){
		NSArray *rowData = [dataSource.data objectAtIndex:i];
		columnOffset = 0.0;
		MCUserDefaults *defaults = [MCUserDefaults instance];
		for(int column = 0; column < [rowData count]; column++){
			float columnWidth = [[dataSource.columnWidth objectAtIndex:column] floatValue];
			NSString *fieldType = [dataSource.fieldTypes objectAtIndex:column];
			if ([fieldType isEqualToString:@"H"]
				||[fieldType isEqualToString:@"I"]
				||[fieldType isEqualToString:@"K"]
				||[fieldType isEqualToString:@"L"]) {
				NSArray *selectIcons = [[rowData objectAtIndex:column] componentsSeparatedByString:@"::"];
				if ([selectIcons count] > 1) {
					NSString *iconLabel = [selectIcons objectAtIndex:1];
					NSArray *icons = [iconLabel componentsSeparatedByString:@","];
					UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(columnOffset, i * cellHeight, columnWidth - 1, cellHeight - 1)];
					if (i % 2) {
						labelView.backgroundColor = defaults.skin_bgTableEvenColor;
					}
					else {
						labelView.backgroundColor = defaults.skin_bgTableOddColor;
					}
					labelView.tag = i * cellHeight + column + 1000;
					for (int j = 0; j < [icons count]; j++) {
						NSString *icon = [icons objectAtIndex:j];
						UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(28 * j + 5+([icons count]==1?(80-24)/2-5:0), 8, 24, 24)];
						imageView.image = [MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
						imageView.backgroundColor = [UIColor clearColor];
						[labelView addSubview:imageView];
						[imageView release];
					}
					[vRightContent addSubview:labelView];
					[labelView release];
					columnOffset += columnWidth;
					continue;
				}
			}
			UILabel *labelSpace = [[UILabel alloc] init];
			UILabel *label = [[UILabel alloc] init];
			if ([fieldType isEqualToString:@"6"]
				||[fieldType isEqualToString:@"7"]
				||[fieldType isEqualToString:@"E"]
				||[fieldType isEqualToString:@"1"]){
				label.frame = CGRectMake(columnOffset, i * cellHeight, columnWidth - 1 - 7, cellHeight - 1);
				labelSpace.frame = CGRectMake(columnOffset + columnWidth - 1 - 7, i * cellHeight, 7, cellHeight - 1);
				label.textAlignment = UITextAlignmentRight;
			}else {
				labelSpace.frame = CGRectMake(columnOffset, i * cellHeight, 7, cellHeight - 1);
				label.frame = CGRectMake(columnOffset + 7, i * cellHeight, columnWidth - 1 - 7, cellHeight - 1);
				label.textAlignment = UITextAlignmentLeft;
			}
			label.font = [UIFont systemFontOfSize:16.0f];
			label.numberOfLines = 0;
			[label setLineBreakMode:UILineBreakModeTailTruncation];
			NSArray *values = [[rowData objectAtIndex:column] componentsSeparatedByString:@":-:"];
			label.text = [values objectAtIndex:0];
			if ([values count] > 1) {
				label.textColor = [MCFunction hexColor:[NSString stringWithFormat:@"%@64", [values objectAtIndex:1]]];
			}
			if (i % 2) {
				label.backgroundColor = defaults.skin_bgTableEvenColor;
				labelSpace.backgroundColor = defaults.skin_bgTableEvenColor;
			}
			else {
				label.backgroundColor = defaults.skin_bgTableOddColor;
				labelSpace.backgroundColor = defaults.skin_bgTableOddColor;
			}
			label.tag = i * cellHeight + column + 1000;
			labelSpace.tag = i * cellHeight + column + 10000;
			[vRightContent addSubview:labelSpace];
			[vRightContent addSubview:label];
			columnOffset += columnWidth;
			
			if (column == [rowData count]-1 && column == 0) {
				[self addRightArrow:label];
			}
			[label release];
			[labelSpace release];
		}
	}	
}


//-------------------------------以下为事件触发方法----------------------------------------
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
	vTopRight.frame = CGRectMake(0, 0, vRight.contentSize.width, vTopRight.frame.size.height);
	vTopRight.bounds = CGRectMake(scrollView.contentOffset.x, 0, vTopRight.frame.size.width, vTopRight.frame.size.height);
	vTopRight.clipsToBounds = YES;	
	vRightContent.frame = CGRectMake(0, 0,vRight.contentSize.width, contentHeight);
	[self addSubview:vTopRight];
	vRight.frame =CGRectMake(0, 0, self.frame.size.width - cellWidth, vLeft.contentSize.height); 
	[vLeft addSubview:scrollView];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
	scrollView.frame = CGRectMake(0, 0, scrollView.frame.size.width, self.frame.size.height);
	vRightContent.frame = CGRectMake(0, self.cellTitleHeight - vLeft.contentOffset.y, vRight.contentSize.width , contentHeight);
	vTopRight.frame = CGRectMake(0, 0, vRight.contentSize.width, vTopRight.frame.size.height);
	vTopRight.bounds = CGRectMake(0, 0, vRight.contentSize.width, vTopRight.frame.size.height);
	[scrollView addSubview:vTopRight];
	[self addSubview:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if(!decelerate)
		[self scrollViewDidEndDecelerating:scrollView];
}

- (void) dealloc {
	vLeft == nil;
	vRight == nil;
	vRightContent == nil;
	vLeftContent == nil;
	vTopRight == nil;
	[dataObjectName release];
	[layoutName release];
	[listData release];
	[listLayout release];
	[gridType release];
	[buttons release];
	
	[super dealloc];
}


-(void)doAction:(int)row
{
	actionSheetFlag = row;
	
	NSMutableDictionary *record = [[self.listData objectForKey:@"rl"]objectAtIndex:row];
	NSMutableArray *dataButtons = [record objectForKey:@"btn"];
	NSMutableArray *cfgButtons = [[NSMutableArray alloc] init];
	
	if ([self.gridType isEqualToString:@"S"]) {
		NSMutableDictionary *subListConfig = [[listLayout objectForKey:@"slc"] objectAtIndex:tabIndex-1];
		if ([subListConfig objectForKey:@"dbtn"]) {
			cfgButtons =[subListConfig objectForKey: @"dbtn"];
			buttons = [[MCUIToolkit getButtons:dataButtons cfgButtons:cfgButtons] retain];
		}	
	} else {	
		buttons = [dataButtons retain];
	}
	
	if ([buttons count] <= 0) {
		return;
	}
	if ([buttons count] == 1) {
		NSString *pKey = @"";
		if ([record objectForKey:@"key"] != nil) {
			pKey = [record objectForKey:@"key"];
		}
		NSMutableDictionary *button = [buttons objectAtIndex:0];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_rec",@"buttonType",
										   self.dataObjectName,@"dataObjectName",
										   record,@"formData",
										   pKey, @"primaryKey", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:viewController.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:nil 
					   naviController:viewController.navigationController];
		}
		[parameters release];
	} else if ([buttons count] > 1) {
		UIActionSheet *menu = [MCUIToolkit actionSheet:buttons
											   withTag:0
										  withDelegate:self
											 withTitle:@"请选择明细操作"];
		[menu showInView:self.superview.window];
	}
}

//弹出菜单按钮点击事件，当actionSheetFlag等于-1的时候执行列表动作，否则执行列表明细动作
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == [buttons count]) {
		// 按下取消按钮
		return;
	}
	int row = actionSheetFlag;	
	NSMutableDictionary *record = [[self.listData objectForKey:@"rl"]objectAtIndex:row];
	NSMutableDictionary *button = [buttons objectAtIndex:buttonIndex];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	NSString *pKey = @"";
	if ([record objectForKey:@"key"] != nil) {
		pKey = [record objectForKey:@"key"];
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"buttonId",
									   @"list_rec",@"buttonType",
									   self.dataObjectName,@"dataObjectName",
									   record,@"formData",
									   pKey, @"primaryKey", nil];
	
	if ([button objectForKey:@"cfmi"] != nil && ![[button objectForKey:@"cfmi"] isEqualToString:@""]){
		[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
					   parameters:parameters 
				   confirmMessage:[button objectForKey:@"cfmi"] 
				   naviController:viewController.navigationController];
	}else{
		[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
					   parameters:parameters 
				   confirmMessage:nil 
				   naviController:viewController.navigationController];
	}
	[parameters release];
}
@end
